import { Button, Space,Input } from 'antd'
import React, {useState,useEffect } from 'react'
import CustomTable from './customTable'
import CustomModel from './customModel'
import moment from 'moment'
import XLSX from 'xlsx'
import { addMessages, updateMessages,deleteMessages, getMessages,getMessagesById } from '../../api/message'
const Message=()=> {
  const { Search } = Input
  
  const [visible,setVisible]=useState(false)
  const [editType,setEditType]=useState('create')
  const [editMessage,setEditMessage]=useState({})
  //渲染列表数据  
  const [data,setData] =useState([])
  const [total,setTotal] =useState(0)
  const [pageSize,setPageSize] =useState(5)
  const [page,setPage] =useState(1)
   //点击保存
  const save = async(info)=>{
    if(editType === 'create') {
     await addMessages(info)
     getPages(page,pageSize)
    }else{
      await updateMessages(info)
      setData(data.map(msg=>{
        if(msg._id===info._id){
          return info
        }
        return msg
      }))
    }
    setVisible(false)
  }
  //获取数据
  const getPages =async (page,pageSize) =>{
    const res =await getMessages({page,pageSize})
    setData(res.list)
    setTotal(res.total)
    setPageSize(Number(res.pageSize))
    setPage(Number(page))
 }
 useEffect(() => {
  getPages()
}, [])
//查询单个，根据cid 
const onSearch =async cid => {
  const result =await getMessagesById(cid)
  setData(data.filter(res=>res.cid===result.cid))
  // setData(result)
}
//查询后恢复数据
const reloadData = ()=>{
  getPages(page,pageSize)
}
//  useEffect(() => {
//    effect
//    return () => {
//      cleanup
//    }
//  }, [input])
 //修改
  const editMessageHandle = (editMessage)=>{
      setVisible(true)
      setEditType('update')
      setEditMessage(editMessage)
  }
  //删除
  const remove =async (_id) =>{
      await deleteMessages(_id)
      // setData(data.filter(msg=>msg._id!=_id))
      getPages(page,pageSize)
      
  }
  //导出excel
 const exportsExcel = ()=>{
   const infos= [
     ["编号","姓名","性别","身份证号","住址","电话","到访时间"]
   ]
   data.forEach(({_id,name,sex,cid,address,phone,createAt})=>{
     infos.push([_id,name,sex,cid,address,phone,moment(createAt).format("YYYY-MM-DD HH:mm:ss")])
   })
   console.log('导出数据',infos)
   const ws = XLSX.utils.aoa_to_sheet(infos);
    // 创建工作簿
    const wb = XLSX.utils.book_new();
    // 将工作表追加到工作簿中
		XLSX.utils.book_append_sheet(wb, ws, "登记信息");
		// 将内存中工作簿内容写入到具体的文件中
		XLSX.writeFile(wb, "infos.xlsx")
 }
    return (
      <div>
       
        <Space>
          <Button type="primary" onClick={()=>{
            setVisible(true)
            setEditType('create')
          }}>添加</Button>
          <Button type="primary" onClick={exportsExcel}>导出excel</Button>
          <Search
            placeholder="输入cid查询"
            allowClear
            enterButton="查询"
            size="middle"
            
            onSearch={onSearch}
          />
          <Button type="primary" onClick={reloadData}>恢复</Button>
        </Space>
        <CustomTable 
        setEditMessage={editMessageHandle} 
        dataSource={data} 
        total={total} 
        onPageChange={getPages}
        pageSize={pageSize}
        page={page}
        onDelete={_id=>{remove(_id)}}
        />
        <CustomModel 
          visible={visible} 
          onCreate={save} 
          onCancel={()=>{setVisible(false)}} 
          editType={editType}
          editMessage={editMessage}
        />
      </div>
    )
  
}
export default Message